import java.util.HashMap;
import java.util.Map;

public class Solution697 {
    public int findShortestSubArray(int[] nums) {
        Map<Integer,Integer> left=new HashMap<>();
        Map<Integer,Integer> right=new HashMap<>();
        Map<Integer,Integer> count=new HashMap<>();
        int max=0;
        int min=Integer.MAX_VALUE;
        for (int i=0;i<nums.length;i++){
            if (!left.containsKey(nums[i])){
                left.put(nums[i],i);
            }
            right.put(nums[i],i);
            count.put(nums[i],count.getOrDefault(nums[i],0)+1);
            max=Math.max(count.get(nums[i]),max);
        }
        for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
            if (entry.getValue()==max){
                min=Math.min(min,right.get(entry.getKey())-left.get(entry.getKey())+1);
            }
        }
        return min;
    }

    public static void main(String[] args) {
        System.out.println(new Solution697().findShortestSubArray(new int[]{1,2,2,3,1,4,2}));
    }
}
